package com.mb.common.config;

import com.mb.app.constants.Constants;
import com.mb.common.service.impl.RedisReceiver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;

import java.util.ArrayList;
import java.util.List;

/**
 * redis 消息订阅
 * @author liliping
 * @create 2018-05-22 下午5:37
 **/
@Configuration
public class RedisSubListenerConfig {

    //初始化监听器
    @Bean
    RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory,
                                            MessageListenerAdapter listenerAdapter) {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        List topicList = new ArrayList<>();
        topicList.add(new PatternTopic(Constants.RedisTopic.Channel_MSG.getCode()));
        topicList.add(new PatternTopic(Constants.RedisTopic.ProductPVUV_MSG.getCode()));
        topicList.add(new PatternTopic(Constants.RedisTopic.Reg_MSG.getCode()));
        topicList.add(new PatternTopic(Constants.RedisTopic.AppChannel_MSG.getCode()));

        container.addMessageListener(listenerAdapter, topicList);
        return container;
    }

    //利用反射来创建监听到消息之后的执行方法
    @Bean
    MessageListenerAdapter listenerAdapter(RedisReceiver redisReceiver) {
        return new MessageListenerAdapter(redisReceiver, "receiveMessage");
    }

    //使用默认的工厂初始化redis操作模板
    @Bean
    StringRedisTemplate template(RedisConnectionFactory connectionFactory) {
        return new StringRedisTemplate(connectionFactory);
    }
}
